import Redis from 'ioredis';
import { Container } from 'typedi';
import { REDIS_HOST, REDIS_PORT, REDIS_TOKEN_DB, REDIS_ONLINE_DB, REDIS_PASSWORD } from '@config';
import { logger } from '@utils/logger';

export const redisToken = new Redis({
  host: REDIS_HOST || '127.0.0.1',
  port: Number(REDIS_PORT) || 6379,
  password: REDIS_PASSWORD || undefined,
  db: Number(REDIS_TOKEN_DB || 0),
});

export const redisOnline = new Redis({
  host: process.env.REDIS_HOST || '127.0.0.1',
  port: Number(process.env.REDIS_PORT) || 6379,
  password: process.env.REDIS_PASSWORD || undefined,
  db: Number(REDIS_ONLINE_DB) || 1,
});

// 监听 ready / error
redisToken.on('ready', () => logger.info('✅ Token Redis 已就绪'));
redisToken.on('connect', () => logger.info('✅ Token Redis 连接成功'));
redisToken.on('error', err => logger.error('❌ Token Redis 连接错误:', err));

redisOnline.on('ready', () => logger.info('✅ Online Redis 已就绪'));
redisOnline.on('connect', () => logger.info('✅ Online Redis 连接成功'));
redisOnline.on('error', err => logger.error('❌ Online Redis 连接错误:', err));

// 优雅关闭
const gracefulShutdown = () => {
  redisToken.disconnect();
  redisOnline.disconnect();
  logger.info('Redis connection closed');
};
process.on('SIGTERM', gracefulShutdown);
process.on('SIGINT', gracefulShutdown);

// 注册到 typedi
Container.set('REDIS_TOKEN', redisToken);
Container.set('REDIS_ONLINE', redisOnline);
